﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GameDataMgr
{
    private static GameDataMgr instanc = new GameDataMgr();
    public static GameDataMgr Instance { get => instanc; }

    public MusicData musicData;

    public RankData rankData;

    public CacheData cacheData;

    private GameDataMgr()
    {
        LoadCacheData();
    }

    public void LoadMusicConf()
    {
        //初始化音乐配置
        musicData = PlayerPrefsDataMgr.Instance.Load(typeof(MusicData), "MusicData") as MusicData;
        //第一次进入游戏
        if (!musicData.notFirst)
        {
            musicData.music = true;
            musicData.audio = true;
            musicData.musicVolume = 1;
            musicData.audioVolume = 1;
            musicData.notFirst = true;
            PlayerPrefsDataMgr.Instance.Save(musicData, "MusicData");
        }
        BackMusic.Instance.ChangeEnable(musicData.music);
        BackMusic.Instance.ChangeVolume(musicData.musicVolume);
    }

    public void LoadRankData()
    {
        //初始化排行榜
        rankData = PlayerPrefsDataMgr.Instance.Load(typeof(RankData), "RankData") as RankData;
    }

    public void LoadCacheData()
    {
        cacheData = PlayerPrefsDataMgr.Instance.Load(typeof(CacheData), "cacheData") as CacheData;
    }
    public void SaveNickName(string name)
    {
        cacheData.NickName = name;
        PlayerPrefsDataMgr.Instance.Save(cacheData, "CacheData");
    }
    public string GetNickName()
    {
        return cacheData.NickName;
    }

    #region 音乐操作
    public void OpenOrCloseMusic(bool value)
    {
        musicData.music = value;
        PlayerPrefsDataMgr.Instance.Save(musicData, "MusicData");
    }

    public void OpenOrCloseAudio(bool value)
    {
        musicData.audio = value;
        PlayerPrefsDataMgr.Instance.Save(musicData, "MusicData");
    }

    public void ChangeMusicVolume(float value)
    {
        musicData.musicVolume = value;
        PlayerPrefsDataMgr.Instance.Save(musicData, "MusicData");
    }

    public void ChangeAudioVolume(float value)
    {
        musicData.audioVolume = value;
        PlayerPrefsDataMgr.Instance.Save(musicData, "MusicData");
    }
    #endregion

    #region 排行榜操作
    public void AddRank(string name, int score, int time)
    {
        if (rankData.ranks.Count >= 10)
        {
            Rank lastRank = rankData.ranks[rankData.ranks.Count - 1];
            if (time > lastRank.time)
            {
                return;
            }
        }
        rankData.ranks.Add(new Rank(name, score, time));
        rankData.ranks.Sort();
        for (int i= rankData.ranks.Count - 1; i>=10; i++)
        {
            rankData.ranks.RemoveAt(i);
        }
        PlayerPrefsDataMgr.Instance.Save(rankData, "RankData");
    }
    #endregion
}
